package com.up4years.dataapi.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJacksonJsonView;

import com.up4years.controller.base.BaseController;
import com.up4years.dataapi.service.support.OSSService;
import com.up4years.utils.Base64ImgUtil;
import com.up4years.utils.CommonUtil;
@Controller
@RequestMapping("/oss")
public class OSSController extends BaseController {
	Logger logger = Logger.getLogger(OSSController.class);
	@Autowired
	private OSSService oSSService;
	@RequestMapping("/test")
	public String test(){
		return "/oss/test";
	}
	@RequestMapping(value="/upload.htm")
	public ModelAndView upload(HttpServletRequest request,String fileContent,String fileName){
		if(StringUtils.isBlank(fileContent)){
			return new ModelAndView(new MappingJacksonJsonView(),this.getFailResult("未指定文件内容"));
		}
		if(StringUtils.isBlank(fileName)){
			return new ModelAndView(new MappingJacksonJsonView(),this.getFailResult("未指定文件名"));
		}
		InputStream is  = Base64ImgUtil.handleBase64IMG(fileContent.trim());
		Map<String,Object> result = handleUpload(is,fileName, "default");
		if(result==null)return new ModelAndView(new MappingJacksonJsonView(),this.getFailResult("上传失败"));
		return new ModelAndView(new MappingJacksonJsonView(),this.getSuccessResult(result));
 	}
	/**
	 * 通用 上传文件
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/upload.htm",method=RequestMethod.POST)
	public ModelAndView upload(HttpServletRequest request){
		MultipartHttpServletRequest multipartRequest = null;
		try{			
			multipartRequest = (MultipartHttpServletRequest) request;  
			CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file");
			if(file==null){
				return new ModelAndView(new MappingJacksonJsonView(),this.getFailResult("[file]文件内容未指定！"));
			}
		}catch(Exception e){
			return new ModelAndView(new MappingJacksonJsonView(),this.getFailResult("必须指定multipart/form-data"));
		}
		Map<String,Object> result = handleUpload(multipartRequest, "default");
		if(result==null)return new ModelAndView(new MappingJacksonJsonView(),this.getFailResult("上传失败"));
		return new ModelAndView(new MappingJacksonJsonView(),this.getSuccessResult(result));
	}
	/**
	 * 上传商品图片 
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/uploadGoodsImg.htm",method=RequestMethod.GET)
	public ModelAndView uploadGoodsImg(HttpServletRequest request,String fileContent,String fileName){
		if(StringUtils.isBlank(fileContent)){
			return new ModelAndView(new MappingJacksonJsonView(),this.getFailResult("未指定文件内容"));
		}
		if(StringUtils.isBlank(fileName)){
			return new ModelAndView(new MappingJacksonJsonView(),this.getFailResult("未指定文件名"));
		}
		InputStream is  = Base64ImgUtil.handleBase64IMG(fileContent.trim());
		Map<String,Object> result = handleUpload(is,fileName, "goodsImg");
		if(result==null)return new ModelAndView(new MappingJacksonJsonView(),this.getFailResult("上传失败"));
		return new ModelAndView(new MappingJacksonJsonView(),this.getSuccessResult(result));
	}
	/**
	 * 上传商品图片 
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/uploadGoodsImg.htm",method=RequestMethod.POST)
	public ModelAndView uploadGoodsImg(HttpServletRequest request){
		MultipartHttpServletRequest multipartRequest = null;
		try{			
			multipartRequest = (MultipartHttpServletRequest) request;  
			CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file");
			if(file==null){
				return new ModelAndView(new MappingJacksonJsonView(),this.getFailResult("[file]文件内容未指定！"));
			}
		}catch(Exception e){
			return new ModelAndView(new MappingJacksonJsonView(),this.getFailResult("必须指定multipart/form-data"));
		}
		Map<String,Object> result = handleUpload(multipartRequest, "goodsImg");
		if(result==null)return new ModelAndView(new MappingJacksonJsonView(),this.getFailResult("上传失败"));
		return new ModelAndView(new MappingJacksonJsonView(),this.getSuccessResult(result));
	}
	/**
	 * 上传身份证图片
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/uploadIdcardImg.htm",method=RequestMethod.GET)
	public ModelAndView uploadIdcardImg(HttpServletRequest request,String fileContent,String fileName){
		if(StringUtils.isBlank(fileContent)){
			return new ModelAndView(new MappingJacksonJsonView(),this.getFailResult("未指定文件内容"));
		}
		if(StringUtils.isBlank(fileName)){
			return new ModelAndView(new MappingJacksonJsonView(),this.getFailResult("未指定文件名"));
		}
		InputStream is  = Base64ImgUtil.handleBase64IMG(fileContent.trim());
		Map<String,Object> result = handleUpload(is,fileName, "idcardImg");
		if(result==null)return new ModelAndView(new MappingJacksonJsonView(),this.getFailResult("上传失败"));
		return new ModelAndView(new MappingJacksonJsonView(),this.getSuccessResult(result));
	}
	/**
	 * 上传身份证图片
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/uploadIdcardImg.htm",method=RequestMethod.POST)
	public ModelAndView uploadIdcardImg(HttpServletRequest request){
		MultipartHttpServletRequest multipartRequest = null;
		try{			
			multipartRequest = (MultipartHttpServletRequest) request;  
			CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file");
			if(file==null){
				return new ModelAndView(new MappingJacksonJsonView(),this.getFailResult("[file]文件内容未指定！"));
			}
		}catch(Exception e){
			return new ModelAndView(new MappingJacksonJsonView(),this.getFailResult("必须指定multipart/form-data"));
		}
		Map<String,Object> result = handleUpload(multipartRequest, "idcardImg");
		if(result==null)return new ModelAndView(new MappingJacksonJsonView(),this.getFailResult("上传失败"));
		return new ModelAndView(new MappingJacksonJsonView(),this.getSuccessResult(result));
	}
	/**
	 * 上传头像
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/uploadHeadicon.htm",method=RequestMethod.GET)
	public ModelAndView uploadheadIcon(HttpServletRequest request,String fileContent,String fileName){
		if(StringUtils.isBlank(fileContent)){
			return new ModelAndView(new MappingJacksonJsonView(),this.getFailResult("未指定文件内容"));
		}
		if(StringUtils.isBlank(fileName)){
			return new ModelAndView(new MappingJacksonJsonView(),this.getFailResult("未指定文件名"));
		}
		InputStream is  = Base64ImgUtil.handleBase64IMG(fileContent.trim());
		Map<String,Object> result = handleUpload(is,fileName, "headIcon");
		if(result==null)return new ModelAndView(new MappingJacksonJsonView(),this.getFailResult("上传失败"));
		return new ModelAndView(new MappingJacksonJsonView(),this.getSuccessResult(result));
	}
	/**
	 * 上传头像
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/uploadHeadicon.htm",method=RequestMethod.POST)
	public ModelAndView uploadheadIcon(HttpServletRequest request){
		MultipartHttpServletRequest multipartRequest = null;
		try{			
			multipartRequest = (MultipartHttpServletRequest) request;  
			CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file");
			if(file==null){
				return new ModelAndView(new MappingJacksonJsonView(),this.getFailResult("[file]文件内容未指定！"));
			}
		}catch(Exception e){
			return new ModelAndView(new MappingJacksonJsonView(),this.getFailResult("必须指定multipart/form-data"));
		}
		Map<String,Object> result = handleUpload(multipartRequest, "headIcon");
		if(result==null)return new ModelAndView(new MappingJacksonJsonView(),this.getFailResult("上传失败"));
		return new ModelAndView(new MappingJacksonJsonView(),this.getSuccessResult(result));
	}
	/**
	 * 
	 * @param request
	 * @param type
	 * @return 文件名
	 */
	private Map<String,Object> handleUpload(MultipartHttpServletRequest multipartRequest, String type) {
        CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file");  
        String newName = generateFileName(type,file.getOriginalFilename());
        logger.debug("生成文件名：" + newName);  
        boolean result= true;
        try {
			oSSService.simpleUpload(newName, file.getInputStream());
		} catch (IOException e) {
 			e.printStackTrace();
 			result= false;
		}
        if(result){
      		Map<String,Object> map = new HashMap<String,Object>();
      		map.put("base", "http://"+CommonUtil.getALI_BucketName()+"-"+CommonUtil.getALI_ENDPOINT()+"/");
      		map.put("url", newName);
      		return map;
         }else{
        	return null;
        }
 	}
	/**
	 * 
	 * @param request
	 * @param type
	 * @return 文件名
	 */
	private Map<String,Object> handleUpload(InputStream is,String fileName, String type) {
 		String newName = generateFileName(type,fileName);
		logger.debug("生成文件名：" + newName);  
  		oSSService.simpleUpload(newName, is);
  		Map<String,Object> map = new HashMap<String,Object>();
  		map.put("base", "http://"+CommonUtil.getALI_BucketName()+"."+CommonUtil.getALI_ENDPOINT()+"/");
  		map.put("url", newName);
  		return map;
 	}
	/**
	 * 生成文件名
	 * @param type
	 * @param fileName
	 * @return
	 */
 	private String generateFileName(String type,String fileName){
		String suffix = this.getSuffix(fileName);
		String prefix ="images/"+type+"/";
		String newName = prefix + new Date().getTime()+"."+ suffix;
		return newName;
	}
	/**
	 * 获取文件后缀名
	 * @param fileName
	 * @return 文件后缀名
	 */
	private String getSuffix(String fileName){
		if(StringUtils.isBlank(fileName)||!fileName.contains(".")){
			return "";
		}
		String[] array = fileName.split("\\.");
		String suffix = array[array.length-1];
		return suffix;
	}
}
